#include "mcp4725.h"
#include<avr/io.h>


void twi_init(void)
{
	TWBR = 80;
	TWSR&= (~(1<<TWPS1))|(~(1<<TWPS0)); // Prescaler as 1

	/*
	
	F_SCK = F_CPU / (16 + 2*(TWBR)*POW(4,TWPS));
	
	*/
}

int twi_send(unsigned char addr, unsigned char value)
{
	//First send start condition over bus
	TWCR = (1<<TWINT) | (1<<TWSTA) | (1<<TWEN);

	//Wait for it to get done
	while(!(TWCR & (1<<TWINT)));

	//Check if Start was transmitted or not
	if((TWSR & 0xF8) != 0x08)
	return FALSE;

	//Start transmitted now transmit SLA+W
	TWDR = addr; // 1100 000 0 = 0xc0 for MCP4725

	//Clear TWINT flag to start transmission
	TWCR = (1<<TWINT) | (1<<TWEN);

	//Wait for it to get done
	while(!(TWCR & (1<<TWINT)));

	//Check if transmitted successfully 
	if((TWSR & 0xF8)!= 0x18)
	return FALSE;

	//load first data byte into TWDR
	TWDR = 0x60;

	//Clear TWINT flag to start transmission
	TWCR = (1<<TWINT) | (1<<TWEN);

	//Wait for it to get done
	while(!(TWCR & (1<<TWINT)));

	//Check if transmitted successfully 
	if((TWSR & 0xF8)!= 0x28)
	return FALSE;

	//load first data byte into TWDR
	TWDR =value;

	//Clear TWINT flag to start transmission
	TWCR = (1<<TWINT) | (1<<TWEN);

	//Wait for it to get done
	while(!(TWCR & (1<<TWINT)));

	//Check if transmitted successfully 
	if((TWSR & 0xF8)!= 0x28)
	return FALSE;

	//load first data byte into TWDR
	TWDR = 0xF0;

	//Clear TWINT flag to start transmission
	TWCR = (1<<TWINT) | (1<<TWEN);

	//Wait for it to get done
	while(!(TWCR & (1<<TWINT)));

	//Check if transmitted successfully 
	if((TWSR & 0xF8)!= 0x28)
	return FALSE;

	//Now transmit STOP condition

	TWCR = (1<<TWINT) | (1<<TWEN) | (1<<TWSTO);

	return TRUE;

}




